package com.b511.swpu.cementbackend.controller;

import com.b511.swpu.cementbackend.service.MetaDictService;
import com.b511.swpu.cementbackend.dto.input.MetaDictInputDto;
import com.b511.swpu.cementbackend.entity.MetaDict;
import com.b511.swpu.cementbackend.exception.CementException;
import com.b511.swpu.cementbackend.repository.MetaDictRepository;
import com.b511.swpu.cementbackend.util.enumeration.Code;
import com.b511.swpu.cementbackend.util.R;
import io.swagger.annotations.Api;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;
import java.util.stream.Collectors;

@Api(value = "数据字典", tags = {"数据字典"})
@RestController
@RequestMapping("/dict")
public class MetaDictController {

    private final MetaDictRepository metaDictRepository;

    private final MetaDictService metaDictService;

    public MetaDictController(MetaDictRepository metaDictRepository, MetaDictService metaDictService) {
        this.metaDictRepository = metaDictRepository;
        this.metaDictService = metaDictService;
    }

    @GetMapping
    public R getAllDict() {
        return metaDictService.getDict();
    }

    @GetMapping("/level1")
    @Transactional
    public R getDictLevel1() {
        return R.ok().putData(metaDictRepository.findParentDict(MetaDict.DICT_LEVEL_LENGTH).collect(Collectors.toList()));
    }

    @PostMapping("/{code}")
    public R addDictChild(@PathVariable String code, @RequestBody @Validated MetaDictInputDto metaDictInputDto) {
        return metaDictService.addDictChild(code, metaDictInputDto);
    }

    @PutMapping("/{code}")
    @Transactional
    public R updateDictChild(@PathVariable String code, @RequestBody @Validated MetaDictInputDto metaDictInputDto) {
        metaDictRepository.updateDictName(code, metaDictInputDto.getLabel());
        return R.ok();
    }

    @DeleteMapping("/{code}")
    @Transactional
    public R deleteMetaDict(@PathVariable String code) {
        if (Objects.equals(metaDictRepository.countByCodeStartingWith(code.substring(0, MetaDict.DICT_LEVEL_LENGTH)), 1)) {
            throw new CementException(Code.DELETE_LAST_DICTIONARY);
        }
        metaDictRepository.deleteByCode(code);
        return R.ok();
    }
}
